<?php

namespace app\common\ShaoHuoPay;

use app\common\ShaoHuoPay\Contracts\GatewayApplicationInterface;
use app\common\ShaoHuoPay\Exceptions\GatewayException;
use app\common\ShaoHuoPay\tools\Config;
use app\common\ShaoHuoPay\tools\Str;

class Pay
{
    /**
     * Config.
     *
     * @var Config
     */
    protected $config;

    /**
     * 初始化
     * Pay constructor.
     * @param $config
     */
    public function __construct($config)
    {
        $this->config = new Config($config);
    }

    /**
     * 生成对应支付对象接口
     * @param $method
     * @return GatewayApplicationInterface
     * @throws GatewayException
     */
    protected function create($method)
    {
        // !$this->config->has('log.file') ?: $this->registeLog();

        $gateway = __NAMESPACE__ . '\\Gateways\\' . Str::studly($method);
        if (class_exists($gateway)) {
            return self::make($gateway);
        }

        throw new GatewayException("Gateway [{$method}] Not Exists", 1);
    }

    /**
     * 生成支付网关接口
     * @param $gateway
     * @return mixed
     * @throws GatewayException
     */
    protected function make($gateway)
    {
        $app = new $gateway($this->config);

        if ($app instanceof GatewayApplicationInterface) {
            return $app;
        }

        throw new GatewayException("Gateway [$gateway] Must Be An Instance Of GatewayApplicationInterface", 2);
    }

    /**
     * @param $method
     * @param $params
     * @return GatewayApplicationInterface
     * @throws GatewayException
     */
    public static function __callStatic($method, $params)
    {
        $app = new self(...$params);

        return $app->create($method);
    }
}
